<?php
/**
 * Created by PhpStorm.
 * User: mohuani
 * Date: 2019/4/14
 * Time: 22:27
 */

namespace App\Services;


//use App\Utils\Util;

class WeatherByCityKeyService extends BaseService
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @param $cityKey
     * @return array
     */
    public function weatherInfoCityKey($cityKey):array
    {
        $redisGetOpt = self::$redis->get(WEATHER_INFO_CITY_KEY_REDIS_KEY . $cityKey);
        if ($redisGetOpt === false) {
            // 如果在redis中获取不到该城市的信息，就调用接扣查询一下对应的天气，并把信息回写到redis
            $curl = curl_init();
            $url = WEATHER_API_BY_CITY_KEY . $cityKey;  //

            $curlRes = self::$util->curlRequest($curl, $url);
            $curlRes = json_decode($curlRes, true);

            if (isset($curlRes['status']) && $curlRes['status'] == WEATHER_API_OK_STATUS_CODE) {
                self::$redis->setex(WEATHER_INFO_CITY_KEY_REDIS_KEY . $cityKey, WEATHER_INFO_REDIS_EXPIRE_TIME, json_encode($curlRes['data'], JSON_UNESCAPED_UNICODE));
                $weatherInfo = $curlRes['data'];
            } else {
                var_dump("cityKey:" . $cityKey . " | msg:天气信息查询失败 | url:" . $url);
                $weatherInfo = [];
            }

        } else {
            $weatherInfo = json_decode($redisGetOpt, true);
        }

        return $weatherInfo;
    }
}